﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using WebMatrix.WebData;
using TYStudio;

namespace TYStudio.UI.AdminTools.Controllers
{
    //[Authorize(Roles="系统管理员")]
    [AllowAnonymous]
    [InitializeSimpleMembership]
    public class UserController : Controller
    {
        private TYStudioMembershipContext db = new TYStudioMembershipContext();

        //
        // GET: /User/

        public ActionResult Index()
        {
            List<UserViewModel> userList = new List<UserViewModel>();
            List<TYStudioMembership> list = new List<TYStudioMembership>();
            using (TYStudioMembershipContext db = new TYStudioMembershipContext())
            {
                list = db.TYStudioMemberships.Include("Roles").ToList();
                foreach (var bm in list)
                {
                    UserViewModel user = new UserViewModel();
                    user.User_ID = bm.UserId;
                    user.User_Name = db.UserProfiles.Single(e => e.UserId == bm.UserId).UserName;
                    user.Email = db.UserProfiles.Single(e => e.UserId == bm.UserId).Email;
                    var roleNameString = "";
                    for (int i = 0; i < bm.Roles.Count; i++)
                    {
                        if (i == 0)
                        {
                            roleNameString = bm.Roles.ElementAt(i).RoleName;
                        }
                        else
                        {
                            roleNameString = roleNameString + "," + bm.Roles.ElementAt(i).RoleName;
                        }
                    }
                    user.Role_Name = roleNameString;
                    userList.Add(user);
                }
            }

            ViewData["UserList"] = userList;
            return View(userList);
        }

        [AllowAnonymous]
        public ActionResult Create()
        {
            ViewData["RoleSelectList"] = GetRoleSelectList();
            return View();
        }

        //
        // POST: /User/Create

        [AllowAnonymous]
        [HttpPost]
        public ActionResult Create(FormCollection collection, string[] roles)
        {
            if (ModelState.IsValid)
            {
                string userName = collection.Get("User_Name");
                string password = collection.Get("Password");
                string email = collection.Get("Email");
                if (db.UserProfiles.SingleOrDefault(e => e.UserName == userName) == null)
                {
                    WebSecurity.CreateUserAndAccount(userName, password);
                    if (roles != null)
                    {
                        foreach (var roleName in roles)
                        {
                            Roles.AddUserToRole(userName, roleName);
                        }
                    }

                    UserProfile user = db.UserProfiles.Single(e => e.UserName == userName);
                    user.Email = email;
                    db.SaveChanges();

                    return RedirectToAction("Index");
                }
                else
                {
                    ViewData["RoleSelectList"] = GetRoleSelectList();
                    TempData["ErrorMessage"] = "用户名已存在";
                }
            }

            return View();
        }

        //
        // GET: /User/Edit/5

        public ActionResult Edit(int id = 0)
        {
            UserViewModel vModel = new UserViewModel();
            List<SelectListItem> roleList = GetRoleSelectList();

            TYStudioMembership membership = db.TYStudioMemberships.Include("Roles").Single(e => e.UserId == id);
            UserProfile user = db.UserProfiles.Single(e => e.UserId == id);
            vModel.User_ID = user.UserId;
            vModel.User_Name = user.UserName;
            vModel.Email = user.Email;
            db.SaveChanges();
            ViewData["RoleSelectList"] = roleList;

            return View(vModel);
        }

        //
        // POST: /User/Edit/5

        [HttpPost]
        public ActionResult Edit(FormCollection collection, string[] roles)
        {
            int id = int.Parse(collection.Get("User_ID"));
            string userName = collection.Get("User_Name");
            string email = collection.Get("Email");

            UserProfile user = db.UserProfiles.Single(e => e.UserId == id);
            user.UserName = userName;
            user.Email = email;
            db.SaveChanges();

            return RedirectToAction("Index");
        }

        public ActionResult EditRole(int id = 0)
        {
            UserViewModel vModel = new UserViewModel();
            List<SelectListItem> roleList = GetRoleSelectList();
            using (TYStudioMembershipContext db = new TYStudioMembershipContext())
            {
                TYStudioMembership membership = db.TYStudioMemberships.Include("Roles").Single(e => e.UserId == id);
                UserProfile user = db.UserProfiles.Single(e => e.UserId == id);
                vModel.User_ID = user.UserId;
                vModel.User_Name = user.UserName;
                vModel.Email = user.Email;

                foreach (var item in roleList)
                {
                    foreach (var role in membership.Roles)
                    {
                        if (item.Value == role.RoleName)
                        {
                            item.Selected = true;
                        }
                    }
                }
            }
            ViewData["RoleSelectList"] = roleList;

            return View(vModel);
        }

        //
        // GET: /User/Delete/5

        public ActionResult Delete(int id)
        {
            Membership.DeleteUser(db.UserProfiles.Single(e => e.UserId == id).UserName);
            db.TYStudioMemberships.Remove(db.TYStudioMemberships.Single(e => e.UserId == id));
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        public ActionResult ResetPassword(int id)
        {
            UserProfile user = db.UserProfiles.Single(e=>e.UserId == id);
            UserViewModel vModel = new UserViewModel();
            vModel.User_ID = user.UserId;
            vModel.User_Name = user.UserName;
            vModel.Email = user.Email;
            return View(vModel);
        }

        [HttpPost]
        public ActionResult ResetPassword(FormCollection collection)
        {
            int id = int.Parse(collection.Get("User_ID"));
            string newPassword = collection.Get("NewPassword");
            UserProfile user = db.UserProfiles.Single(e=>e.UserId == id);
            TYStudioMembership membership = db.TYStudioMemberships.Single(e=>e.UserId == id);
            string passwordResetToken = WebSecurity.GeneratePasswordResetToken(user.UserName,1440);
            membership.PasswordResetToken = passwordResetToken;
            WebSecurity.ResetPassword(passwordResetToken, newPassword);
            TempData["SuccessMessage"] = "密码修改成功！";
            return View();
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

        private List<SelectListItem> GetRoleSelectList()
        {
            List<SelectListItem> roleList = new List<SelectListItem>();
            using (TYStudioMembershipContext db = new TYStudioMembershipContext())
            {
                foreach (var role in db.Roles)
                {
                    SelectListItem item = new SelectListItem();
                    item.Value = role.RoleName;
                    item.Text = role.RoleName;
                    roleList.Add(item);
                }
            }
            return roleList;
        }
    }
}